package com.shchuangzhi.smartguard;

import android.app.Application;
import android.os.Environment;

import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.flattener.ClassicFlattener;
import com.elvishew.xlog.formatter.message.throwable.DefaultThrowableFormatter;
import com.elvishew.xlog.formatter.stacktrace.DefaultStackTraceFormatter;
import com.elvishew.xlog.printer.AndroidPrinter;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.iflytek.cloud.SpeechUtility;
import com.shchuangzhi.smartguard.core.AppCrashHandler;
import com.shchuangzhi.smartguard.core.Clock;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.ImageLoader;
import com.shchuangzhi.smartguard.core.Job;
import com.shchuangzhi.smartguard.core.JobManager;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.NotifyPrinter;
import com.shchuangzhi.smartguard.core.command.Command;
import com.shchuangzhi.smartguard.core.command.DecisionCommand;
import com.shchuangzhi.smartguard.core.command.SyncProfileCommand;
import com.shchuangzhi.smartguard.core.receiver.SyncReceiverDataCommand;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.text.SimpleDateFormat;

import okhttp3.OkHttpClient;

/**
 * Created by j_hu on 4/17/17.
 */

public class SmartGuardApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        initLog();
        AppCrashHandler.instance().init();

        initStetho();
        startJobs();

        ImageLoader.getInstance().init(getApplicationContext());

        CrashReport.initCrashReport(getApplicationContext(), "2d164d8f9e", true);

        SpeechUtility.createUtility(SmartGuardApplication.this, "appid=" + getString(R.string.app_id));

        registerActivityLifecycleCallbacks(new SmartGuardActivityLifecycleCallbacks());
    }

    private void initLog() {
        LogConfiguration config = new LogConfiguration.Builder()
                .logLevel(LogLevel.ALL)
                .tag(getString(R.string.global_log_tag))
                .stackTraceFormatter(new DefaultStackTraceFormatter())
                .throwableFormatter(new DefaultThrowableFormatter())
                .build();
        Printer filePrinter = new FilePrinter
                .Builder(new File(Environment.getExternalStorageDirectory(), "smartguard").getPath())
                .fileNameGenerator(new DateFileNameGenerator())
                .logFlattener(new ClassicFlattener())
                .build();
        Printer droidPrinter = new AndroidPrinter();
        XLog.init(config, droidPrinter, filePrinter, NotifyPrinter.getInstance());
    }

    private void startJobs() {
        JobManager.add(new Job(Consts.JOB_CURRENT_TIME_PRINT,
                Consts.INTERVAL_CURRENT_TIME_PRINT,
                new Job.JobExecutor() {
                    @Override
                    public Object Execute() {
                        return String.format("%s：%s", Consts.TERMINAL_TIME_DESC, new SimpleDateFormat("MM月dd日 E HH:mm:ss").format(Clock.now()));
                    }
                }));

        final Command cmd = new DecisionCommand();
        JobManager.add(new Job(Consts.JOB_DATA_SYNC,
                Consts.INTERVAL_DATA_SYNC,
                new Job.JobExecutor() {
                    @Override
                    public Object Execute() {
                        return cmd.runPost();
                    }
                }, cmd));

        final Command receiverDataSyncCommand = new SyncReceiverDataCommand();
        JobManager.add(new Job(Consts.JOB_RECEIVER_DATA_SYNC,
                Consts.INTERVAL_RECEIVER_DATA_SYNC,
                new Job.JobExecutor() {
                    @Override
                    public Object Execute() {
                        return receiverDataSyncCommand.runPost();
                    }
                }, receiverDataSyncCommand));

        final Command healthCheckCmd = new SyncProfileCommand();
        JobManager.add(new Job(Consts.JOB_NETWORK_CHECK,
                Consts.INTERVAL_HEALTHCHECK,
                new Job.JobExecutor() {
                    @Override
                    public Object Execute() {
                        return healthCheckCmd.runGet();
                    }
                }, healthCheckCmd));

        Mode.getInstance().startAuto();
        JobManager.startAll();
    }

    private void initStetho() {
        Stetho.initializeWithDefaults(this);
        new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())
                .build();
    }

//    private void initImageLoader(Context context) {
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration
//                .Builder(context)
//                .memoryCacheExtraOptions(200,200)
//                .threadPoolSize(3)
//                .threadPriority(Thread.NORM_PRIORITY - 2)
//                .denyCacheImageMultipleSizesInMemory()
//                .memoryCache(new LruMemoryCache(10 * 1024 * 1024))
//                .memoryCacheSize(10 * 1024 * 1024)
//                .diskCacheSize(200 * 1024 * 1024)
//                .diskCacheFileCount(1000)
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
//                .tasksProcessingOrder(QueueProcessingType.LIFO)
//                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
//                .imageDownloader(new BaseImageDownloader(context, 5* 1000, 30 * 1000))
//                .build();
//        ImageLoader.getInstance().init(config);
//    }
}
